<template>
  <div class="page-container">
    <!-- <van-nav-bar left-arrow title="经营总览" @click-left="onClickLeft" fixed placeholder /> -->

    <div class="main-content">
      <div class="blue-bg">
        <van-tabs v-model="activeTab" @change="onTabChange" line-width="40" color="white" title-active-color="white"
          title-inactive-color="#a3d5ff" sticky :offset-top="0">
          <van-tab :title="tab.title" v-for="tab in tabs" :key="tab.id">
            <div class="tab-content">
              <!-- 总金额 -->
              <div class="amount-section flex-wrap flex-center flex-sb">
                <p>
                  <span class="currency">¥</span>
                  <span class="amount">{{ tab.amount }}</span>
                </p>
                <van-tag round type="primary" class="yoy-tag">同比 {{ tab.yoy }}</van-tag>
              </div>
              <div class="unit">单位：万元</div>
              <!-- 图表 -->
              <div class="chart-container">
                <div v-if="tab.id !== 'income'" ref="gaugeChart" class="gauge-chart"></div>
                <div v-if="tab.id === 'income'" ref="lineChart" class="line-chart"></div>
              </div>
              <!-- 下方统计 -->
              <div class="stats-section flex-wrap flex-center">
                <div class="stat-item">
                  <div class="stat-value"><span class="unit" style="margin-right:2px;">¥</span>{{ tab.stat1.value }}
                    <span class="unit">万元</span>
                  </div>
                  <div class="stat-label">{{ tab.stat1.label }}</div>
                </div>
                <div class="stat-divider"></div>
                <div class="stat-item">
                  <div class="stat-value"><span class="unit" style="margin-right:2px;">¥</span>{{ tab.stat2.value }}
                    <span class="unit">万元</span>
                  </div>
                  <div class="stat-label">{{ tab.stat2.label }}</div>
                </div>
              </div>
            </div>
          </van-tab>
        </van-tabs>
      </div>
      <!-- 饼图 -->
      <div class="white-card">
        <div class="card-header flex-wrap flex-center flex-sb">
          <h3 class="card-title">{{ bottomChartTitle }}</h3>
        </div>
        <div class="donut-chart-container flex-wrap flex-center">
          <div ref="donutChart" class="donut-chart"></div>
          <div class="donut-legend">
            <div v-for="item in donutData" :key="item.name" class="legend-item">
              <span class="legend-color" :style="{ backgroundColor: item.color }"></span>
              <span class="legend-name">{{ item.name }}</span>
              <span class="legend-value">{{ item.value }} 万元</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts/core';
import { GaugeChart, LineChart, PieChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { GetCurrContractInfo } from '@/api/interface'

echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  GaugeChart,
  LineChart,
  PieChart,
  CanvasRenderer
]);

export default {
  name: 'BusinessOverview',
  components: {
  },
  data() {
    return {
      activeTab: 0,
      tabs: {
        contract: {
          id: 'contract',
          title: '当年合同',
          amount: 0,
          yoy: '+0%',
          completion: 0,
          stat1: { value: 0, label: '当前剩余合同额' },
          stat2: { value: 0, label: '待签合同额' },
          donutData: [
            { value: 0, name: '总包事业部', color: '#5470c6' },
            { value: 0, name: '建筑分院', color: '#91cc75' },
            { value: 0, name: '规划分院', color: '#fac858' },
            { value: 0, name: '公路分院', color: '#ee6666' },
            { value: 0, name: '市政分院', color: '#73c0de' },
            { value: 0, name: '石化分院', color: '#3ba272' },
            { value: 0, name: '其它分院', color: '#fc8452' },
          ]
        },
        collection: {
          id: 'collection',
          title: '当年收款',
          amount: 0,
          yoy: '+0%',
          completion: 0,
          stat1: { value: 0, label: '财务应收款' },
          stat2: { value: 0, label: '经营应收款' },
          donutData: [
            { value: 0, name: '总包事业部', color: '#5470c6' },
            { value: 0, name: '建筑分院', color: '#91cc75' },
            { value: 0, name: '规划分院', color: '#fac858' },
            { value: 0, name: '公路分院', color: '#ee6666' },
            { value: 0, name: '市政分院', color: '#73c0de' },
            { value: 0, name: '石化分院', color: '#3ba272' },
            { value: 0, name: '其它分院', color: '#fc8452' },
          ]
        },
        income: {
          id: 'income',
          title: '当年收入',
          amount: 0,
          yoy: '+0%',
          lineDataX: [],
          lineData: [],
          stat1: { value: 0, label: '经营应收款' },
          stat2: { value: 0, label: '已签订金额' },
          donutData: [
            { value: 0, name: '总包事业部', color: '#5470c6' },
            { value: 0, name: '建筑分院', color: '#91cc75' },
            { value: 0, name: '规划分院', color: '#fac858' },
            { value: 0, name: '公路分院', color: '#ee6666' },
            { value: 0, name: '市政分院', color: '#73c0de' },
            { value: 0, name: '石化分院', color: '#3ba272' },
            { value: 0, name: '其它分院', color: '#fc8452' },
          ]
        }
      },
      gaugeChartInstance: null,
      lineChartInstance: null,
      donutChartInstance: null,
    };
  },
  computed: {
    currentTabData() {
      return Object.values(this.tabs)[this.activeTab];
    },
    bottomChartTitle() {
      const titles = ['各部门合同情况', '各部门收款情况', '各部门收入情况'];
      return titles[this.activeTab];
    },
    donutData() {
      return this.currentTabData.donutData;
    }
  },
  watch: {
    activeTab() {
      this.$nextTick(() => {
        this.updateCharts();
      });
    }
  },
  created() {
    this.getData()
  },
  mounted() {
    // setTimeout(() => {
    //   this.initCharts();
    // }, 300)
  },
  methods: {
    getData() {
      GetCurrContractInfo().then(res => {
        let r = JSON.parse(res)
        if (r.success) {
          // 合同
          let contract = r.data['CurrContract']
          this.tabs.contract.amount = contract.Unit
          this.tabs.contract.yoy = `+${contract.Comparison}%`
          this.tabs.contract.completion = contract.Completion
          this.tabs.contract.stat1.value = contract.LeftContractAmount
          this.tabs.contract.stat2.value = contract.SignContractAmount
          this.tabs.contract.donutData.forEach((item, i) => {
            const f = contract.DeptInfo.find(d => d.name === item.name)
            this.tabs.contract.donutData[i].value = f ? f.text : 0
          })
          // 收款
          let collection = r.data['CurrReceipt']
          this.tabs.collection.amount = collection.Unit
          this.tabs.collection.yoy = `+${collection.Comparison}%`
          this.tabs.collection.completion = collection.Completion
          this.tabs.collection.stat1.value = collection.AccountsAmount
          this.tabs.collection.stat2.value = collection.ReceivablesAmount
          this.tabs.collection.donutData.forEach((item, i) => {
            const f = collection.DeptInfo.find(d => d.name === item.name)
            this.tabs.collection.donutData[i].value = f ? f.text : 0
          })
          // 收入
          let income = r.data['CurrIncome']
          this.tabs.income.amount = income.Unit
          this.tabs.income.yoy = `+${income.Comparison}%`
          this.tabs.income.completion = income.Completion
          this.tabs.income.stat1.value = income.ReceivablesAmount
          this.tabs.income.stat2.value = income.SignContractAmount
          this.tabs.income.donutData.forEach((item, i) => {
            const f = income.DeptInfo.find(d => d.name === item.name)
            this.tabs.income.donutData[i].value = f ? f.text : 0
          })
          this.tabs.income.lineDataX = income.LineIncomeInfo.map(i => `${i.name}月`)
          this.tabs.income.lineData = income.LineIncomeInfo.map(i => i.text)
          this.initCharts();
        }
      })
    },
    onClickLeft() {
      this.$router.push('/projectPrev')
    },
    onTabChange() {
    },
    initCharts() {
      this.initGaugeChart();
      this.initDonutChart();
    },
    updateCharts() {
      if (this.currentTabData.id === 'income') {
        if (this.lineChartInstance) {
          this.lineChartInstance.dispose();
          this.lineChartInstance = null;
        }
        this.initLineChart();
      } else {
        if (this.gaugeChartInstance) {
          this.gaugeChartInstance.dispose();
          this.gaugeChartInstance = null;
        }
        this.initGaugeChart();
      }
      this.updateDonutChart();
    },
    initGaugeChart() {
      const gaugeRef = this.$refs.gaugeChart[this.activeTab];
      if (!gaugeRef) return;
      this.gaugeChartInstance = echarts.init(gaugeRef);
      const option = {
        series: [
          {
            type: 'gauge',
            radius: '93%',
            startAngle: 90,
            endAngle: -270,
            min: 0,
            max: 100,
            splitNumber: 5,
            itemStyle: {
              color: '#fff',
            },
            progress: {
              show: true,
              roundCap: true,
              width: 15,
              itemStyle: {
                color: 'white'
              }
            },
            axisLine: {
              lineStyle: {
                width: 15,
                color: [[1, 'rgba(255, 255, 255, 0.3)']]
              }
            },
            axisTick: {
              show: false
            },
            splitLine: {
              show: false,
            },
            axisLabel: {
              show: false,
            },
            pointer: {
              show: false
            },
            title: {
              show: false
            },
            detail: {
              valueAnimation: true,
              offsetCenter: [0, '-10%'],
              fontSize: 30,
              fontWeight: 'bold',
              color: 'white',
              formatter: function (value) {
                return value + '%';
              }
            },
            data: [
              {
                value: this.currentTabData.completion,
                detail: {
                  label: '完成度',
                  valueAnimation: true
                }
              }
            ]
          },
          { // For the label "完成度"
            type: 'gauge',
            startAngle: 90,
            endAngle: -270,
            min: 0,
            max: 100,
            data: [{ value: this.currentTabData.completion }],
            axisLine: { show: false },
            splitLine: { show: false },
            axisTick: { show: false },
            axisLabel: { show: false },
            pointer: { show: false },
            detail: {
              show: true,
              offsetCenter: ['0', '30%'],
              color: '#afd6ff',
              fontSize: 14,
              formatter: '完成度'
            }
          }
        ],
        animation: true,
        animationDuration: 500,
        animationEasing: 'quadraticOut',
        animationDurationUpdate: 500,
        animationEasingUpdate: 'bounceOut'
      };
      this.gaugeChartInstance.setOption(option);
      // this.gaugeChartInstance.resize();
    },
    initLineChart() {
      const lineRef = this.$refs.lineChart[0];
      if (!lineRef) return;
      this.lineChartInstance = echarts.init(lineRef, null, { renderer: 'canvas' });
      const option = {
        grid: { top: 30, right: 20, bottom: 50, left: 30 },
        xAxis: {
          type: 'category',
          data: this.tabs.income.lineDataX,
          axisLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.5)' } },
          axisLabel: { color: 'white' },
          axisTick: { show: false }
        },
        yAxis: {
          type: 'value',
          axisLabel: { color: 'white' },
          splitLine: { lineStyle: { color: 'rgba(255, 255, 255, 0.2)' } }
        },
        tooltip: {
          trigger: 'axis'
        },
        series: [{
          data: this.currentTabData.lineData,
          type: 'line',
          smooth: true,
          symbol: 'circle',
          symbolSize: 8,
          itemStyle: { color: '#fff' },
          lineStyle: { color: '#fff', width: 3 },
        }]
      };
      this.lineChartInstance.setOption(option);
      // this.lineChartInstance.resize();
    },
    initDonutChart() {
      const donutRef = this.$refs.donutChart;
      if (!donutRef) return;
      this.donutChartInstance = echarts.init(donutRef, null, { renderer: 'canvas' });
      const option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          show: false
        },
        series: [
          {
            name: this.bottomChartTitle,
            type: 'pie',
            radius: ['60%', '80%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: false,
              }
            },
            labelLine: {
              show: false
            },
            data: this.donutData,
          }
        ]
      };
      this.donutChartInstance.setOption(option);
      // this.donutChartInstance.resize();
    },
    updateDonutChart() {
      if (!this.donutChartInstance) {
        this.initDonutChart();
      } else {
        const option = {
          series: [
            {
              name: this.bottomChartTitle,
              data: this.donutData
            }
          ]
        };
        this.donutChartInstance.setOption(option);
        // this.donutChartInstance.resize();
      }
    },
  },
  beforeDestroy() {
    if (this.gaugeChartInstance) {
      this.gaugeChartInstance.dispose();
    }
    if (this.lineChartInstance) {
      this.lineChartInstance.dispose();
    }
    if (this.donutChartInstance) {
      this.donutChartInstance.dispose();
    }
  }
};
</script>

<style lang="scss" scoped>
@import '../../sass/base.scss';
@import '../../sass/mixin.scss';

.page-container {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.main-content {
  padding-bottom: 3px;

  .blue-bg {
    background-color: #007aff;
    color: white;
    padding: 0 16px 16px;
    border-bottom-left-radius: 20px;
    border-bottom-right-radius: 20px;
  }

  /deep/ .van-tabs__wrap {
    border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  }

  /deep/ .van-tabs__nav {
    background-color: transparent;
  }

  /deep/ .van-tabs--sticky .van-tabs__nav {
    background-color: #007aff;
  }

  /deep/ .van-hairline--bottom::after {
    border-bottom-width: 0;
  }

  /deep/ .van-tabs__line {
    background-color: white;
    height: 3px;
    border-radius: 3px;
  }

  .tab-content {
    text-align: center;
  }

  .amount-section {
    padding-top: 20px;

    .currency {
      font-size: 18px;
    }

    .amount {
      font-size: 24px;
      font-weight: bold;
      font-family: 'DIN-Bold', sans-serif;
    }

    .yoy-tag {
      background-color: rgba(255, 255, 255, 0.2);
      border: none;
      margin-left: 8px;
      color: #a01e1e;
      padding: 4px 10px;

      &::after {
        border: none;
      }
    }
  }

  .unit {
    font-size: 11px;
    color: rgba(255, 255, 255, 0.8);
    text-align: left;
  }

  .chart-container {
    height: 240px;
    width: 100%;
    position: relative;

    .gauge-chart,
    .line-chart {
      width: 100%;
      height: 240px;
    }
  }

  .stats-section {
    justify-content: space-around;
    padding: 16px 0;

    .stat-item {
      text-align: center;
    }

    .stat-value {
      font-size: 18px;
      font-weight: bold;
      font-family: 'DIN-Bold', sans-serif;

      .unit {
        font-size: 12px;
        font-weight: normal;
        font-family: sans-serif;
      }
    }

    .stat-label {
      font-size: 12px;
      color: rgba(255, 255, 255, 0.8);
      margin-top: 4px;
    }

    .stat-divider {
      width: 1px;
      height: 30px;
      background-color: rgba(255, 255, 255, 0.3);
    }
  }

  .white-card {
    background-color: white;
    margin: -20px 16px 16px;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }

  .card-header {

    .card-title {
      margin: 0;
      font-size: 16px;
      font-weight: bold;
    }
  }

  .donut-chart-container {
    margin-top: 10px;

    .donut-chart {
      width: 50%;
      height: 160px;
    }

    .donut-legend {
      width: 50%;
      display: flex;
      flex-direction: column;
      justify-content: center;

      .legend-item {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        font-size: 12px;

        .legend-color {
          width: 8px;
          height: 8px;
          border-radius: 50%;
          margin-right: 8px;
        }

        .legend-name {
          color: #646566;
          flex: 1;
          margin-right: 8px;
        }

        .legend-value {
          color: #323233;
          font-family: 'DIN-Bold', sans-serif;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
